//
//  AppDelegate.swift
//  weibo
//
//  Created by yanghong on 15/12/5.
//  Copyright © 2015年 杨鸿. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var observer: NSObjectProtocol?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        // 判断用户是否登录 没有登录,点击
        window?.rootViewController = WBUserAccountViewModel.sharedAccount.userLogon ?
            defaultRootViewController() : WBViewController()
        
        window?.makeKeyAndVisible()
        
        // print(NSBundle.mainBundle().infoDictionary)
        
        //注册通知
        observer = NSNotificationCenter.defaultCenter().addObserverForName(WBSwitchRootVCNotification, object: nil, queue: nil, usingBlock: { (notify) -> Void in
            // 对传过来的 `self` 进行判断  并跳转到相应的控制器
            if notify.object is WBOAuthViewController {
               print("切换控制器")
            self.window?.rootViewController = WBWelcomeViewController()
                
            }else{
             
            self.window?.rootViewController = WBViewController()
            
            }
        })
        
        return true
    }
   // MARK -判断版本
    private func defaultRootViewController() ->UIViewController {
        /**
        *   如果有新版本则跳转到新特性页面,没有新版本跳刀欢迎页面
        *
        *  @return 返回控制器
        */
        if hasNewVersion() {
        
          return WBNewfeatureViewController()
        }else{
        
             return WBWelcomeViewController()
        
        }

    }
    // 判断是否有新版本
   private func hasNewVersion() -> Bool {
    
     let versionKEY = "versionKEY"
     let localVersion = NSUserDefaults.standardUserDefaults().stringForKey(versionKEY)
    
      //取出本地版本号
     let currentVsersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
      // 保存当前的版本号到偏好设置
    NSUserDefaults.standardUserDefaults().setObject(currentVsersion, forKey: versionKEY)
      // 开发中的比较版本号尽量要使用字符串去比较
    if let local = localVersion where currentVsersion.compare(local) != NSComparisonResult.OrderedDescending {
    
       return false
    
    }
        return true
    }
           
    deinit{
    
       NSNotificationCenter.defaultCenter().removeObserver(observer!)
    
    }
}